import 'package:boss/color_constant.dart';
import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/form/new_base_text_form_field.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hi_common/hi_common.dart';

class StaffGratuityPage extends StatefulWidget {
  @override
  StaffGratuityPageState createState() => StaffGratuityPageState("小费设置");

  StaffGratuityPage({Key key}) : super(key: key);
}

class StaffGratuityPageState extends BaseState<StaffGratuityPage> {
  StaffGratuityPageState(String pageName) : super(pageName);

  TextEditingController _textEditing0 = TextEditingController();
  TextEditingController _textEditing1 = TextEditingController();
  TextEditingController _textEditing2 = TextEditingController();

  //tab集合
  List<Map> tabMapObj = [
    {"name": '固定小费金额', "id": 0, "icon": '¥'},
    {"name": '订单百分比金额', "id": 1, "icon": '%'}
  ];

  int _type = 0; //0 钱数 1 百分比

  //用户账号当前在使用的type
  int useType;

  //接口接受data
  dynamic acceptData;

  //arr 输入框数值
  List<dynamic> dataArrInputNum = [null, null, null];

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds: 0), () async {
      obtainDataListWait();
    });
  }

  @override
  void dispose() {
    _textEditing0.dispose();
    _textEditing1.dispose();
    _textEditing2.dispose();
    super.dispose();
  }

  //获取list 数据
  obtainDataListWait() async {
    showLoadingToast();
    try {
      await Future.wait<dynamic>([
        obtainDataList('fixed'),
        obtainDataList('percent'),
      ]).then((v) {
        if (v[0].length != 0) {
          useType = 0;
        }
        if (v[1].length != 0) {
          useType = 1;
        }
        acceptData = v;

        if (acceptData != null && _type == 0 && acceptData[0].length != 0) {
          dataArrInputNum = [
            AmountUtil.price2String(acceptData[0][0]["firstLevel"] ?? 0),
            AmountUtil.price2String(acceptData[0][0]["secondLevel"] ?? 0),
            AmountUtil.price2String(acceptData[0][0]["thirdLevel"] ?? 0)
          ];
          _textEditing0.text = dataArrInputNum[0];
          _textEditing1.text = dataArrInputNum[1];
          _textEditing2.text = dataArrInputNum[2];
        }
        if (acceptData != null && _type == 1 && acceptData[1].length != 0) {
          dataArrInputNum = [
            AmountUtil.price2String(acceptData[1][0]["firstLevel"] ?? 0),
            AmountUtil.price2String(acceptData[1][0]["secondLevel"] ?? 0),
            AmountUtil.price2String(acceptData[1][0]["thirdLevel"] ?? 0)
          ];
          _textEditing0.text = dataArrInputNum[0];
          _textEditing1.text = dataArrInputNum[1];
          _textEditing2.text = dataArrInputNum[2];
        }

        setState(() {});
      }).catchError((e) {});
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  obtainDataList(String tipType) async {
    var res = await api.tipSettingGet(tipType);
    if (res.successful()) {
      return res.data;
    } else {
      toast(res.msg);
      return [];
    }
  }

  //新增
  tipSettingUpdate(
    String type,
    int firstLevel,
    int secondLevel,
    int thirdLevel,
  ) async {
    showLoadingToast();
    try {
      var res = await api.tipSettingAdd({
        'tipType': type,
        'firstLevel': firstLevel,
        'secondLevel': secondLevel,
        'thirdLevel': thirdLevel,
      });
      if (res.successful()) {
        toast("保存成功");
        obtainDataListWait();
        setState(() {});
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  _pageBody() {
    return Column(
      children: <Widget>[
//        Row(
//          children: <Widget>[
//            Expanded(
//              child:InkWell(
//                onTap:(){
//                  moneyAndpercentageOnTap(true);
//                },
//                child: Container(
//                  child:Text("¥"),
//                ),
//              ),
//            ),
//            Expanded(
//              child:InkWell(
//                onTap:(){
//                  moneyAndpercentageOnTap(false);
//
//                },
//                child: Container(
//                  child:Text("%"),
//                ),
//              ),
//            ),
//
//          ],
//        ),

        Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(
                0.w,
              ),
              boxShadow: [
                BoxShadow(color: Color.fromRGBO(249, 249, 249, 1), offset: Offset(0.0, 3.0), blurRadius: 0.1, spreadRadius: 0.6),
              ]),
          padding: EdgeInsets.only(
            left: 30.w,
            right: 30.w,
          ),
          height: 138.w,
          child: Container(
            child: Row(
              children: tabMapObj
                  .map((item) => Expanded(
                        child: InkWell(
                          onTap: () {
                            if (item["id"] == _type) {
                              return;
                            }

                            _type = item["id"];

                            if (_type != useType) {
                              dataArrInputNum = [null, null, null];
                              _textEditing0.text = '';
                              _textEditing1.text = '';
                              _textEditing2.text = '';
                            } else {
                              if (acceptData != null && _type == 0 && acceptData[0].length != 0) {
                                dataArrInputNum = [
                                  AmountUtil.price2String(acceptData[0][0]["firstLevel"] ?? 0),
                                  AmountUtil.price2String(acceptData[0][0]["secondLevel"] ?? 0),
                                  AmountUtil.price2String(acceptData[0][0]["thirdLevel"] ?? 0)
                                ];
                                _textEditing0.text = dataArrInputNum[0];
                                _textEditing1.text = dataArrInputNum[1];
                                _textEditing2.text = dataArrInputNum[2];
                              }
                              if (acceptData != null && _type == 1 && acceptData[1].length != 0) {
                                dataArrInputNum = [
                                  AmountUtil.price2String(acceptData[1][0]["firstLevel"] ?? 0),
                                  AmountUtil.price2String(acceptData[1][0]["secondLevel"] ?? 0),
                                  AmountUtil.price2String(acceptData[1][0]["thirdLevel"] ?? 0)
                                ];
                                _textEditing0.text = dataArrInputNum[0];
                                _textEditing1.text = dataArrInputNum[1];
                                _textEditing2.text = dataArrInputNum[2];
                              }
                            }

                            setState(() {});
                          },
                          child: Container(
                            child: Center(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.spaceAround,
                                children: <Widget>[
                                  Stack(
                                    children: <Widget>[
                                      Container(
                                        width: 200.w,
                                        child: Padding(
                                          padding: EdgeInsets.only(
                                            top: 10.w,
                                          ),
                                          child: Center(
                                            child: Text(
                                              "${item["icon"]}",
                                              style: (_type == item["id"]) ? TextStyleConstant().blue_32 : TextStyleConstant().normal_2_32,
                                            ),
                                          ),
                                        ),
                                      ),
                                      Positioned(
                                        top: 2.w,
                                        right: 0,
                                        child: useType != item["id"]
                                            ? Container()
                                            : Container(
                                                decoration: BoxDecoration(
                                                    color: ColorConstant.ff5770f6,
                                                    borderRadius: BorderRadius.only(topLeft: Radius.circular(12.w), bottomRight: Radius.circular(12.w))),
                                                child: Padding(
                                                  padding: EdgeInsets.symmetric(
                                                    horizontal: 3.w,
                                                  ),
                                                  child: Text(
                                                    "使用中",
                                                    style: TextStyleConstant().white_24,
                                                  ),
                                                ),
                                              ),
                                      ),
                                    ],
                                  ),
                                  Text(
                                    "${item["name"]}",
                                    style: (_type == item["id"]) ? TextStyleConstant().blue_32 : TextStyleConstant().normal_2_32,
                                  ),
                                  Container(
                                    width: 30,
                                    height: 6.w,
                                    decoration: BoxDecoration(
                                      color: _type == item["id"] ? ColorConstant.ff5770f6 : Color.fromARGB(1, 1, 1, 0),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                  ),
                                  SizedBox(
                                    height: 6.w,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ))
                  .toList(),
            ),
          ),
        ),
        SizedBox(
          height: 10.w,
        ),
        Expanded(
          child: Padding(
            padding: EdgeInsets.only(
              left: 30.w,
              right: 30.w,
            ),
            child: SingleChildScrollView(
              child: Column(
                children: (dataArrInputNum ?? [])
                    .asMap()
                    .keys
                    .map((item) => Container(
                          child: Row(
                            children: <Widget>[
//                        Text("___${dataArrInputNum[item]}"),
                              Expanded(
                                child: BaseMoneyTextFormField(
                                  moneyPattern: true,
                                  inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
//                            enabled:false,
                                  controller: (item == 0
                                      ? _textEditing0
                                      : item == 1
                                          ? _textEditing1
                                          : _textEditing2),
                                  maxLength: 8,
                                  keyboardType: TextInputType.number,
                                  prefixText: '${item + 1}、小费金额',
                                  isRequired: true,
                                  hintText: '${_type == 0 ? '请输入显示小费金额' : '请输入百分比,不得超过100'}',
                                  initialValue: (dataArrInputNum[item] == null ? '' : dataArrInputNum[item].toString()),

                                  onChanged: (value) {
                                    if (value == '') {
                                      dataArrInputNum[item] = null;
                                      return null;
                                    } else {
                                      var controller = (item == 0
                                          ? _textEditing0
                                          : item == 1
                                              ? _textEditing1
                                              : _textEditing2);

                                      if (controller.text == '.') {
                                        controller.text = '';
                                      }
                                      if (controller.text.split(".").length > 2) {
                                        controller.text = controller.text.split(".")[0] + '.' + controller.text.split(".")[1];
                                      }
                                      if (controller.text.split(".").length == 2) {
                                        if (controller.text.split(".")[1].length > 2) {
                                          controller.text = controller.text.split(".")[0] + '.' + (controller.text.split(".")[1]).substring(0, 2);
                                        }
                                      }

                                      dataArrInputNum[item] = value;
                                    }
                                    setState(() {});
                                  },
                                ),
                              ),
                              Text(
                                " ${_type == 0 ? '¥' : '%'}",
                                style: TextStyleConstant().normal_1_28,
                              ),
                            ],
                          ),
                        ))
                    .toList(),
              ),
            ),
          ),
        ),
        FixedBottomBtn(
          title: "保存",
          onTap: () async {
            var dataArrNotNullbool = dataArrInputNum.firstWhere((item) => item == null, orElse: () => false);
            if (dataArrNotNullbool == null) {
              toast('三个小费不可为空，请检查');
              return null;
            }
            if (_type == 1) {
              var dataArrNumOverRange = dataArrInputNum.firstWhere((item) => ((num.parse(item)) > 100), orElse: () => false);
              if (dataArrNumOverRange != false) {
                toast('百分比不得大于100%');
                return null;
              }
            }
            int numCount(_num) {
//            print(int.parse(((num.parse(_num))*100).toStringAsFixed(0)));
              return int.parse(((num.parse(_num)) * 100).toStringAsFixed(0));
            }

            //fixed 钱 percent 百分比 firstLevel:0,int secondLevel,int thirdLevel
            tipSettingUpdate(_type == 0 ? "fixed" : "percent", numCount(dataArrInputNum[0]), numCount(dataArrInputNum[1]), numCount(dataArrInputNum[2]));
          },
          isShowShadow: false,
        )

//        FixedBottomDoubleBtn(
//          first:"清除",
//          second: '保存',
//          onFirst: () async {
//
//          },
//          onSecond: () async {
//            var dataArrNotNullbool = dataArrInputNum.firstWhere(
//                    (item) => item == null,
//                orElse: () => false);
//
//          if(dataArrNotNullbool==null){
//
//              toast('表单填写不完整');
//              return null;
//          }
//          if(_type==1){
//            var dataArrNumOverRange = dataArrInputNum.firstWhere(
//                    (item) => (item>100),
//                orElse: () => false);
//            if(dataArrNumOverRange!=false){
//              toast('百分比不得大于100%');
//              return null;
//            }
//          }
//          },
//          isShowShadow: true,
//        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return _pageBody();
  }
}
